package com.lb.shopguide.ui.fragment.guide.order;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterGoodsInOrderCommon;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.ExpressBean;
import com.lb.shopguide.entity.ShipInfo;
import com.lb.shopguide.entity.order.GoodsInOrderBean;
import com.lb.shopguide.event.guide.SelectExpressEvent;
import com.lb.shopguide.event.guide.SendGoodsEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.activity.ScanActivity;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * Created by kang on 2017/6/5.
 * 发货页面
 */

public class FragmentSendGoods extends BaseCommonFragment {
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.layout_delivery_company)
    RelativeLayout layoutDeliveryCompany;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_client_name)
    TextView tvClientName;
    @BindView(R.id.tv_order_code)
    TextView tvOrderNum;
    @BindView(R.id.tv_receiver_name)
    TextView tvReceiverName;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_express_company)
    TextView tvExpressCompany;
    @BindView(R.id.tv_send_goods)
    TextView tvSendGoods;
    @BindView(R.id.tv_bill_code)
    TextView tvBillCode;
    @BindView(R.id.layout_scanner)
    RelativeLayout layoutBill;
    @BindView(R.id.iv_scanner)
    ImageView ivScanner;

    private ShipInfo mShipInfo;
    private String mOrderNum;

    private List<GoodsInOrderBean> mGoodsInOrderList;
    private AdapterGoodsInOrderCommon mAdapterGoodsInOrderCommon;

    private ExpressBean mExpressBean;
    private String billCode;




    public static FragmentSendGoods newInstance(String orderNum) {
        FragmentSendGoods fragmentSendGoods = new FragmentSendGoods();
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.ORDER_CODE, orderNum);
        fragmentSendGoods.setArguments(bundle);
        return fragmentSendGoods;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_send_goods;
    }

    @Override
    public void initData() {
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.ORDER_CODE)) {
            mOrderNum = bundle.getString(AppConstant.ORDER_CODE);
            sendRequestGetShipInfo();
        }

        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {

        ntb.setTitleText("发货");
        ntb.setLeftImageSrc(R.drawable.iv_back);
        ntb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapterGoodsInOrderCommon = new AdapterGoodsInOrderCommon(R.layout.layout_goods_base_gray, mGoodsInOrderList);
        mRecyclerView.setAdapter(mAdapterGoodsInOrderCommon);

    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentSendGoods.class.getName();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    private void bindShipInfo() {
        tvReceiverName.setText(mShipInfo.getReceipter() + "    " + mShipInfo.getConnectTel());
        tvOrderNum.setText(mShipInfo.getOrderNum());
//        tvExpressCompany.setText(mShipInfo.get);
        tvClientName.setText(mShipInfo.getReceipter());
        tvAddress.setText(mShipInfo.getAddress());

        mGoodsInOrderList = mShipInfo.getOrderDetailList();
        mAdapterGoodsInOrderCommon.setNewData(mGoodsInOrderList);
    }


    @Subscribe
    public void onExpressSelect(SelectExpressEvent event) {
        mExpressBean = event.getExpressBean();
        tvExpressCompany.setText(mExpressBean.getExpressCorpName());
    }

    private void sendRequestGetShipInfo() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    mShipInfo = (ShipInfo) JsonUtil.getObject(response.getReturnContent(), ShipInfo.class);
                    bindShipInfo();
                }
            }
        };
        ApiMethodGuide.getShipInfo(new SimpleLbObserver(listener, otherListener), mOrderNum,this, FragmentEvent.DESTROY_VIEW);
    }

    private void sendRequestSendGoods(String expressCode, String expressBill) {
        HashMap hashMap = new HashMap();
        hashMap.put("orderNum", mOrderNum);
        hashMap.put("expressCorpCode", expressCode);
        hashMap.put("expressBill", expressBill);
        RequestBody body = BizUtil.getBodyFromMap(hashMap);
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {
            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == (ResponseCode.RESPONSE_SUCCESS)) {
                    EventBus.getDefault().post(new SendGoodsEvent());
                    ToastUtils.showShort("发货成功");
                    pop();
                } else {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        };
        ApiMethodGuide.commitSendGoods(new SimpleLbObserver(listener, otherListener), body,this, FragmentEvent.DESTROY_VIEW);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == AppConstant.REQUEST_CODE_SCAN) {
                String qrCode = data.getExtras().getString(AppConstant.QR_CODE);
                tvBillCode.setText(qrCode);
            }
        }
    }

    @OnClick(R.id.layout_delivery_company)
    void deliverCompanyClick() {
        start(FragmentSelectDelivery.newInstance());
    }

    @OnClick(R.id.tv_send_goods)
    void sendGoods() {
        if (mExpressBean == null) {
            ToastUtils.showShort("请选择快递公司");
            return;
        }
        billCode = tvBillCode.getText().toString();
        if (TextUtils.isEmpty(billCode)) {
            ToastUtils.showShort("请输入快递单号");
            return;
        }
        sendRequestSendGoods(mExpressBean.getExpressCorpCode(), billCode);
    }

    @OnClick(R.id.iv_scanner)
    void scanClick() {
        Intent intent = new Intent(mContext, ScanActivity.class);
        startActivityForResult(intent, AppConstant.REQUEST_CODE_SCAN);
    }

    @OnClick(R.id.layout_scanner)
    void layoutScanClick() {
        //输入订单号
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_enter_billcode, null);
        final EditText etCode = view.findViewById(R.id.et_nickname);
        etCode.setHint("请输入快递单号");
        if (!TextUtils.isEmpty(billCode)) {
            etCode.setText(billCode);
            etCode.setSelection(billCode.length());//将光标移至文字末尾
        }
        android.support.v7.app.AlertDialog dialog = new android.support.v7.app.AlertDialog.Builder(mContext).setTitle(" ")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        billCode = etCode.getText().toString();
                        tvBillCode.setText(billCode);
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setView(view).create();
        dialog.show();
    }
}
